package com.yhc.order.server.exception;

import com.yhc.common.dto.BaseResult;
import com.yhc.common.exception.ResponseEnum;
import com.yhc.common.util.ResultUtil;
import com.yhc.common.util.ServletUtil;
import com.yhc.order.server.consts.RequestHeader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Configuration
@RestControllerAdvice(basePackages = "com.yhc.order")
public class OrderExceptionHandler {

    @org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)
    private BaseResult<?> handleException(Exception e) {
        log.error("# request error", e);
        String requestId = getRequestId();
        return ResultUtil.error( ResponseEnum.ERROR.getMessage() + "-" + requestId);
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(OrderServiceException.class)
    private BaseResult<?> handleAccessException(OrderServiceException se) {
        return ResultUtil.fail(se);
    }

    @org.springframework.web.bind.annotation.ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult<?> exceptionHandle(MethodArgumentNotValidException me) {
        log.warn("# {}", me.getMessage());
        return ResultUtil.fail(me.getMessage());
    }


    @org.springframework.web.bind.annotation.ExceptionHandler(MissingServletRequestParameterException.class)
    public BaseResult<?> exceptionHandle(MissingServletRequestParameterException me) {
        log.warn("# {}", me.getMessage());
        return ResultUtil.fail(me.getMessage());
    }

    private String getRequestId() {
        HttpServletRequest request = ServletUtil.getRequest();
        String requestId = request.getHeader(RequestHeader.REQUEST_ID);
//        if (StringUtils.isBlank(requestId) || requestId.length() <= 8) {
//            return requestId;
//        }
        return requestId.substring(requestId.length() - 8, requestId.length());
    }

}
